package userserv

import (
	"codedef"
	"encoding/json"
	"log"
	"net/http"
	"rhelper"
)

func setSpeed(w http.ResponseWriter, r *http.Request) {
	type setSpeedAction struct {
		Cid   string `json:"cid"`
		Speed string `json:"speed"`
	}

	var uniqueId string
	uniqueId = r.Header.Get("uniqueId")

	log.Printf("setSpeed, uniqueId:%s\n", uniqueId)

	message := make([]byte, r.ContentLength)
	n, _ := r.Body.Read(message)
	if n != int(r.ContentLength) {
		log.Println("setSpeed failed, can't read request body")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	var action setSpeedAction
	err := json.Unmarshal(message, &action)
	if err != nil {
		log.Println("setSpeed failed, json decode failed:", err)
		replyError(w, codedef.ERR_DECODE)
		return
	}

	errCode := checkDevCtrlAction(action.Cid, uniqueId)
	if errCode != codedef.ERR_SUCCEED {
		log.Println("setSpeed failed, check task error:", err)
		replyError(w, codedef.ERR_OPRATION_FAILD)
		return
	}

	type Message struct {
		Uri string `json:"uri"`
		Pwm int    `json:"pwm"`
	}

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	msg := Message{}
	msg.Uri = "/setFanSpeed"
	msg.Pwm = convertSpeed2Pwm(action.Speed)

	log.Println("messge: ", msg)

	controller := getOnlineControllerById(action.Cid)
	if controller == nil {
		log.Println("syncPlan2Device failed, no online controller for:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_OFFLINE)
		return
	}

	if controller.isBusy() {
		log.Println("syncPlan2Device failed, controller is busy:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_BUSY)
		return
	}

	if wait := syn2Device(*controller, msg); wait != nil {
		// log.Println("start to reply app.", string(wait))

		devMessage, errCode := parserDevReply(wait)
		if 0 != errCode {
			replyError(w, codedef.ERR_OPRATION_FAILD)
			return
		}

		replyBuffer(w, devMessage)
		//go GetRuntimeInfo(w, controller)
	} else {
		log.Println("save setSpeed failed, error:", err)
		replyError(w, codedef.ERR_CONTROLLER_NO_RESPONSE)
		return
	}
}

func init() {
	myMux.muxHandlers.HandleFunc("/setSpeed", setSpeed)
}
